package com.ehotting.eaf.netty.client;

import com.alibaba.fastjson.JSON;
import com.ehotting.eaf.netty.sync.SyncFutureMapHelper;
import com.ehotting.eaf.netty.domain.DataAble;
import com.ehotting.eaf.netty.loggers.NettyMsgSendLogger;
import org.slf4j.MDC;

public class TcpClientHelper {

	private TcpClient tcpClient;

	private SyncFutureMapHelper<DataAble> syncFutureMapHelper;

	private NettyMsgSendLogger logger;

	public void request(DataAble data){
		if(data==null){
			return;
		}
		MDC.put(NettyMsgSendLogger.REQUEST, JSON.toJSONString(data));
		try{
			tcpClient.send(data);
		}catch (Exception e){
			MDC.put(NettyMsgSendLogger.EXCEPTION,"request error");
			throw  e;
		}finally{
			logger.info();
		}

	}

	public DataAble request(DataAble data,boolean sync) {
		MDC.put(NettyMsgSendLogger.REQUEST, JSON.toJSONString(data));
		MDC.put(NettyMsgSendLogger.START_TIME, String.valueOf(System.currentTimeMillis()));

		DataAble msg = null;
		try {
			if(sync) {
				syncFutureMapHelper.set(data.getSerial());
			}
			tcpClient.send(data);
			if(sync) {
				msg = syncFutureMapHelper.get(data.getSerial());
				MDC.put(NettyMsgSendLogger.RESPONSE, JSON.toJSONString(msg));
			}
		} catch (InterruptedException e) {
			MDC.put(NettyMsgSendLogger.EXCEPTION,"request time out(10s)");
			e.printStackTrace();
		}finally{
			logger.info();
		}

		return msg;
	}

	/**
	 *
	 * @param data 数据实体
	 * @param timeout 超时，单位：秒
	 * @param sync 是否同步
	 * @return
	 */
	public DataAble request(DataAble data,long timeout,boolean sync){
		MDC.put(NettyMsgSendLogger.REQUEST, JSON.toJSONString(data));
		MDC.put(NettyMsgSendLogger.START_TIME, String.valueOf(System.currentTimeMillis()));

		DataAble msg = null;

		try {
			if(sync ) {
				syncFutureMapHelper.set(data.getSerial());
			}
			tcpClient.send(data);
			if(sync ) {
				msg = syncFutureMapHelper.get(data.getSerial(), timeout);
				MDC.put(NettyMsgSendLogger.RESPONSE, JSON.toJSONString(msg));
			}
		} catch (InterruptedException e) {
			MDC.put(NettyMsgSendLogger.EXCEPTION,"request time out("+timeout+"s)");
			e.printStackTrace();
		}finally{
			logger.info();
		}

		return msg;
	}

	public void response(DataAble data){
		syncFutureMapHelper.putAndNotify(data.getSerial(), data);
	}

	public void setTcpClient(TcpClient tcpClient) {
		this.tcpClient = tcpClient;
	}

	public void setSyncFutureMapHelper(SyncFutureMapHelper<DataAble> syncFutureMapHelper) {
		this.syncFutureMapHelper = syncFutureMapHelper;
	}

	public void setLogger(NettyMsgSendLogger logger) {
		this.logger = logger;
	}



}